package com.vincent.template.commons.base;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.jpa.repository.support.JpaRepositoryImplementation;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

import javax.persistence.EntityManager;
import java.io.Serializable;

/**
 * @author Vincent Wang
 * @date 2021/3/26 10:29
 */
public class BaseJpaRepositoryFactoryBean<R extends JpaRepository<T, K>, T, K extends Serializable>
        extends JpaRepositoryFactoryBean<R, T, K> {

    public BaseJpaRepositoryFactoryBean(Class<? extends R> repositoryInterface) {
        super(repositoryInterface);
    }

    @Override
    protected RepositoryFactorySupport createRepositoryFactory(EntityManager em) {
        return new BaseJpaRepositoryFactory<>(em);
    }

    private static class BaseJpaRepositoryFactory<T, K extends Serializable>
            extends JpaRepositoryFactory {

        private final EntityManager em;

        public BaseJpaRepositoryFactory(EntityManager em) {
            super(em);
            this.em = em;
        }

        @Override
        protected JpaRepositoryImplementation<T, K> getTargetRepository(RepositoryInformation information,
                                                                        EntityManager em) {
            return new BaseJpaRepositoryImpl<>((Class<T>) information.getDomainType(),
                    (Class<K>) information.getIdType(), em);
        }

        @Override
        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
            return BaseJpaRepositoryImpl.class;
        }
    }

}
